package cosplay.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cosplay.DAO.PhotoDAOImpl;
import cosplay.DAO.UserDAOImpl;
import cosplay.beans.PhotoInfos;
import cosplay.beans.Photos;
@Controller (value="photocontroler")
public class PhotoController extends MultiActionController {
	@Autowired
	private PhotoDAOImpl photodao;
	@Autowired
	private UserDAOImpl userdao;
	private Cache cache=CacheManager.create().getCache("COSPLAY_CACHE");

	@RequestMapping(value="/photoedit.htm",method=RequestMethod.GET)
	protected ModelAndView handleshowedit(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		int id=Integer.valueOf(req.getParameter("id")).intValue();
		PhotoInfos photoinfo=photodao.get(id);
		ModelMap model=new ModelMap();
		model.addAttribute("photo",photoinfo);
		return new ModelAndView("photomodify","model",model);
	}
	
	@RequestMapping(value="/photoedit.htm",method=RequestMethod.POST)
	protected ModelAndView handelactedit(HttpServletRequest req,HttpServletResponse res) throws Exception
	{
		PhotoInfos photoinfo=getPhotoInfoFromReq(req, SecurityContextHolder.getContext().getAuthentication().getName());
		photoinfo.setId(Integer.valueOf(req.getParameter("id")).intValue());
		photodao.edit(photoinfo, photoinfo.getId());
		photoinfo=photodao.get(photoinfo.getId());
		ModelMap model=new ModelMap();
		model.addAttribute("photo", photoinfo);
		model.addAttribute("message", "update successed");
		return new ModelAndView("photomodify","model",model);
		
	}

	@RequestMapping(value="/photoupload.htm",method=RequestMethod.GET)
	protected ModelAndView handleshowupload(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		return new ModelAndView("photoupload");
	}
	
	@RequestMapping(value="/photoupload.htm",method=RequestMethod.POST)
	protected ModelAndView handelactupload(HttpServletRequest req, HttpServletResponse res)throws Exception
	{
		Photos photo=getPhotoFromReq((MultipartHttpServletRequest) req, SecurityContextHolder.getContext().getAuthentication().getName());
		photodao.addRaw(photo);
		String message="Successed add an other photo";
		ModelMap model=new ModelMap();
		model.addAttribute("message",message);
		return new ModelAndView("photoupload","model",model);
	}

	@RequestMapping(value="/showall.htm")
	protected ModelAndView handleshowall(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		int page=0;
		if(cosplay.Services.FileServices.Stringintcheck(req.getParameter("page")))
			page=Integer.valueOf(req.getParameter("page")).intValue();
		ModelMap model=new ModelMap();
		model.addAttribute("target","showallphotos.htm");
		model.addAttribute("page",page);
		return new ModelAndView("photolistajax","model",model);
	}
	
	@RequestMapping(value="/showallphotos.htm")
	protected ModelAndView handleshowallcontent(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		long start=System.currentTimeMillis();
//		Map<String, List<Integer>>  cacheresult=null;
		if(cosplay.Services.CacheServices.getFromCache(cache, req.getSession().getId(), "getall", 1)==null)
		{
			List<Integer> ids=photodao.getAllId();
			cosplay.Services.CacheServices.insertToCache(cache, "getall", req.getSession().getId(), ids, 10);
		}
		System.out.println("Access from session:"+req.getSession().getId()+"");
//		if (cache.isElementInMemory(req.getSession().getId()))
//		{
//			cacheresult=(Map<String,List<Integer>>) cache.get(req.getSession().getId()).getValue();
//		}
//		if ((cacheresult==null)||(cacheresult.get("getallresultcount")==null))
//		{
//			List<Integer> photoids=photodao.getAllId();
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			photoids.addAll(photoids);
//			Map<String,List<Integer>> allphoto=new HashMap<String,List<Integer>>();
//			List<Integer> temp=null;
//			int j=0;
//			for(int i=0;i<=photoids.size();i++)
//			{
//				if ((j*10==i)||(i==photoids.size()))
//				{
//					if(j!=0)
//					{
//						allphoto.put("getallpage"+(j)+"", temp);
//					}
//					if(i==photoids.size())
//					{
//						allphoto.put("getallpage"+(j)+"", temp);
//						break;
//					}
//					temp=new ArrayList<Integer>();
//					j++;
//				}
//				temp.add(photoids.get(i));
//			}
//			temp=new ArrayList<Integer>();
//			temp.add(photoids.size());
//			allphoto.put("getallresultcount", temp);
//			cache.put(new Element(req.getSession().getId(),allphoto));
//		}
		System.out.println("prepare cache taks:"+(System.currentTimeMillis()-start)+"ms");
		start=System.currentTimeMillis();
		int page=1;
		if(cosplay.Services.FileServices.Stringintcheck(req.getParameter("page")))
		{
			page=Integer.valueOf(req.getParameter("page")).intValue();
		}
//		cacheresult=(Map<String, List<Integer>>) cache.get(req.getSession().getId()).getValue();
//		cacheresult.get(req.getSession().getId());
//		List<Integer> idlist = cacheresult.get("getallpage"+page+"");
		List<Integer> idlist =cosplay.Services.CacheServices.getFromCache(cache, req.getSession().getId(), "getall", page);
		int resultcount=cosplay.Services.CacheServices.getCountFromCache(cache, req.getSession().getId(), "getall");
		int pageresultcount=idlist.size();
		int pagecount=((resultcount/10)*10==resultcount)?(resultcount/10):((resultcount/10)+1);
		List<PhotoInfos> photo=new ArrayList<PhotoInfos>();
		List<List<Integer>> rawids=new ArrayList<List<Integer>>();
		for (int id:idlist)
		{
			photo.add(photodao.get(id));
			rawids.add(photodao.getRawByPhoto(id));
		}
		System.out.println("prepare photo taks:"+(System.currentTimeMillis()-start)+"ms");
		start=System.currentTimeMillis();
		ModelMap model=new ModelMap();
		model.addAttribute("photo", photo);
		model.addAttribute("rawid", rawids);
		//model.addAttribute("resultcount",resultcount);
		//model.addAttribute("pagecount",pagecount);
		//model.addAttribute("currentpage", page);
		model.addAttribute("pageresultcount", pageresultcount);
		res.addIntHeader("resultcount",resultcount);
		res.addIntHeader("pagecount",pagecount);
		res.addIntHeader("currentpage",page);
		//res.addIntHeader("pageresultcount",pageresultcount);
		System.out.println("prepare model taks:"+(System.currentTimeMillis()-start)+"ms");
		return new ModelAndView("photolisttest","model",model);
//		if (cacheresult!=null)
//		{
//			@SuppressWarnings("unchecked")
//			Map<String, List<Integer>> resultmap =(Map<String,List<Integer>>) cacheresult;
//			List<Integer> idlist =(List<Integer>) resultmap.get("getall");
//			if (idlist!=null)
//			{
//				int page=Integer.valueOf(req.getParameter("page")).intValue();
//				idlist=idlist.subList((page-1)*10, (page*10-1)>idlist.size()?idlist.size():(page*10-1));
//				List<PhotoInfos> photo=new ArrayList<PhotoInfos>();
//				for (int id:idlist)
//				{
//					photo.add(photodao.get(id));
//				}
//				ModelMap model=new ModelMap();
//				model.addAttribute("photo", photo);
//				return new ModelAndView("photolist","model",model);
//			}
//		}
//		long start=System.currentTimeMillis();
//		List<Integer> photoids=photodao.getAllId();
//		List<PhotoInfos> photo= photodao.getAll();
//		Map<String,List<Integer>> allphoto=new HashMap<String,List<Integer>>();
//		allphoto.put("getall", photoids);
//		cache.put(new Element(req.getSession().getId(),allphoto));
//		photo.addAll(photo);
//		photo.addAll(photo);
//		photo.addAll(photo);
//		photo.addAll(photo);
//		photo.addAll(photo);
//		ModelMap model=new ModelMap();
//		model.addAttribute("photo", photo);
//		int resultcount=photo.size();
//		model.addAttribute("resultcount",resultcount);
//		int pagecount=(resultcount/10)+1;
//		model.addAttribute("pagecount",pagecount);
//		return new ModelAndView("photolist","model",model);
	}
	
	private Photos getPhotoFromReq(MultipartHttpServletRequest req, String uname)
	{
		Photos photo=new Photos();
		try {
			photo.setImage(req.getFile("image").getBytes());
			photo.setPreview(cosplay.Services.FileServices.getpreview(req.getFile("image").getBytes()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		photo.setPhoto(Integer.valueOf(req.getParameter("photoid")).intValue());
		return photo;
	}
	
	private PhotoInfos getPhotoInfoFromReq(HttpServletRequest req,String uname)
	{
		PhotoInfos photo=new PhotoInfos();
		photo.setTitle(req.getParameter("title"));
		photo.setDescription(req.getParameter("description"));
		photo.setUserID(userdao.getByName(uname).getId());
		return photo;
	}
	

}
